import Taro from "@tarojs/taro";
import { getUserInfo, clear } from "@/utils/storage";
/**
 * 简单复制对象
 * 从resource->target
 */
export const copyObject = function copyObject(target, resource) {
  if (typeof target === "undefined") {
    return resource;
  }
  if (typeof resource === "undefined" || resource === null) {
    return target;
  }
  // eslint-disable-next-line no-unused-vars
  for (const key in resource) {
    if (resource.hasOwnProperty(key)) {
      if (resource[key] === null || resource[key] === "undefined") continue;
      target[key] = resource[key];
    }
  }
  return target;
};

const Toast = {
  fail: (title) => {
    Taro.showToast({
      title,
      icon: "none",
      duration: 2000,
    });
  },
};

/**
 * 处理登录验证过期
 */
const handleUnauthorized = () => {
  const { account } = getUserInfo();
  let url = "/pages/login/index";
  if (account) {
    url += `?username=${account}`;
  }
  clear();
  Taro.reLaunch({
    url,
  });
};

/**
 *网络错误状态处理
 */
export const errHandler = (error) => {
  const data = error;

  switch (error.statusCode || error.status) {
    case 401:
      Toast.fail(data.data?.msg || data.message);
      handleUnauthorized();
      break;
    case 403:
      Toast.fail(data.message || "403异常");
      break;
    case 404:
      Toast.fail(data.message || "404异常");
      break;
    case 422:
      Toast.fail("请求参数错误");
      break;
    case 426:
      Toast.fail(data.msg || "请求参数错误");
      break;
    case 428:
      Toast.fail(data.msg || "无效的身份");
      break;
    case 500: {
      const url = error.url || "";
      Toast.fail(url + "-服务器无响应(500)");
      break;
    }

    default:
      Toast.fail(data.msg || "未知的情况");
      break;
  }
};
